#!/usr/bin/env python3
"""
在线考试系统 - 一键启动脚本
"""

import os
import subprocess
import sys
from pathlib import Path

def run_command(command, cwd=None):
    """运行系统命令"""
    try:
        result = subprocess.run(command, shell=True, cwd=cwd, capture_output=True, text=True)
        if result.returncode != 0:
            print(f"错误: {result.stderr}")
            return False
        return True
    except Exception as e:
        print(f"运行命令时出错: {e}")
        return False

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("错误: 需要Python 3.8或更高版本")
        sys.exit(1)
    print("✓ Python版本检查通过")

def check_dependencies():
    """检查依赖"""
    try:
        import fastapi
        import sqlalchemy
        print("✓ Python依赖已安装")
        return True
    except ImportError:
        print("正在安装Python依赖...")
        return run_command("pip install -r backend/requirements.txt")

def check_nodejs():
    """检查Node.js"""
    try:
        result = subprocess.run(["node", "--version"], capture_output=True, text=True)
        if result.returncode == 0:
            print("✓ Node.js已安装")
            return True
    except FileNotFoundError:
        print("错误: 未找到Node.js，请先安装Node.js 16+")
        return False

def setup_frontend(frontend_path, name):
    """设置前端项目"""
    print(f"正在设置{name}端...")
    
    # 安装依赖
    if not run_command("npm install", cwd=frontend_path):
        return False
    
    print(f"✓ {name}端设置完成")
    return True

def create_database():
    """创建数据库"""
    try:
        from backend.app.database import engine
        from backend.app.models import Base
        
        # 创建数据库目录
        db_dir = Path("database")
        db_dir.mkdir(exist_ok=True)
        
        # 创建表
        Base.metadata.create_all(bind=engine)
        print("✓ 数据库表创建成功")
        return True
    except Exception as e:
        print(f"创建数据库失败: {e}")
        return False

def main():
    """主函数"""
    print("🚀 在线考试系统 - 开发环境设置")
    print("=" * 50)
    
    # 检查Python版本
    check_python_version()
    
    # 检查Python依赖
    if not check_dependencies():
        sys.exit(1)
    
    # 检查Node.js
    if not check_nodejs():
        sys.exit(1)
    
    # 创建数据库
    if not create_database():
        sys.exit(1)
    
    # 设置前端项目
    frontend_dirs = [
        ("frontend/student", "学生端"),
        ("frontend/teacher", "教师端"),
        ("frontend/admin", "管理端")
    ]
    
    for path, name in frontend_dirs:
        if not setup_frontend(path, name):
            sys.exit(1)
    
    print("\n🎉 设置完成！")
    print("\n启动命令：")
    print("1. 启动后端: cd backend && uvicorn app.main:app --reload")
    print("2. 启动学生端: cd frontend/student && npm run dev")
    print("3. 启动教师端: cd frontend/teacher && npm run dev")
    print("4. 启动管理端: cd frontend/admin && npm run dev")
    print("\n或使用Docker: docker-compose up -d")

if __name__ == "__main__":
    main()